<!--
 * @Author: 朱自强
 * @Date: 2023-04-20 11:58:35
 * @LastEditors: 朱自强
 * @LastEditTime: 2023-11-10 08:52:03
 * @FilePath: \vite-project\src\components\VoiceInput\VoiceInput.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by 朱自强, All Rights Reserved. 
-->
<template>
  <div :id="`voice-input-div-${pageData.uuid}`" class="voice-input-div">
    <!-- 语音div -->
    <div class="voice">
      <div class="voice-left">
        <n-icon size="24" :component="Keyboard" />
      </div>
      <div class="voice-right">
        <n-button style="height: 32px; width: 100%; background: #fff" @click="voiceStart"> 点我 说话 </n-button>
      </div>
      <!-- 弹出div -->
      <div id="mask-div" v-show="pageData.maskShow"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, reactive, onMounted } from "vue";
import { Keyboard } from "@vicons/carbon";
import Recorder from "js-audio-recorder";
const { proxy }: any = getCurrentInstance();
// 变量
const pageData: any = reactive({
  // 唯一标识
  uuid: proxy.$someUtil.getUUID(),
  // 录音对象
  recorder: null,
  // 录音弹窗是否显示
  maskShow: true,
});
onMounted(() => {
  // 录音配置
  pageData.recorder = new Recorder();
});
// 开始录音
const voiceStart = () => {
  if (pageData.recorder) {
    // 获取麦克风权限
    Recorder.getPermission().then(
      () => {
        // 开始录音
        pageData.recorder.start().then(
          () => {
            // 开始录音
          },
          (error: any) => {
            // 出错了
            console.log(`开始录音报错 : ${error.message}`);
            alert(`开始录音报错 : ${error.message}`);
          }
        );
        // 录音后回调
        pageData.recorder.onprogress = function (params: any) {
          // 录音后回调获取到到音频数据
          console.log("🚀 ~ file: VoiceInput.vue:54 ~ 录音后回调获取到到音频数据:", params);
        };
      },
      (error: any) => {
        console.log(`获取权限报错 : ${error.message}`);
        alert(`获取权限报错 : ${error.message}`);
      }
    );
  }
  pageData.maskShow = true;
};
</script>

<style lang="less" scoped>
.voice-input-div {
  position: relative;
}
// 语音
.voice {
  border: solid orange 1px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  height: 48px;
  background-color: #f5f6f7;
  padding: 0px 10px;
  // gap: 10px;
}
// 左侧
.voice-left {
  padding-right: 10px;
}
// 右侧
.voice-right {
  flex: 1;
}
// 录音弹出窗口
#mask-div {
  border: solid black 1px;
  position: absolute;
  // width: 100%;
  height: 300px;
  left: 0;
  right: 0;
  bottom: 49px;
  z-index: 9;
}
</style>
<style>
/* 去掉按钮边框 */
.voice-right .n-button .n-button__border {
  border: none !important;
}
</style>
